// https://leetcode.cn/problems/3sum/description/


class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> temp;
        sort(nums.begin(), nums.end());
        int n = nums.size() - 1;
        int k = 100000000;
        int i;
        for (i = 0; i <= n - 2; i++) 
        {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int l = i + 1, r = n;
            k = -nums[i];
            while (l < r) {
                if (nums[l] + nums[r] > k) {
                    r--;   
                } else if (nums[l] + nums[r] < k) {
                    l++;
                } else {
                    temp.push_back({nums[i], nums[l], nums[r]});
                    while ((r - 1> l) && nums[r] == nums[r - 1]) {
                        r--;
                    }
                    while ((l +1< r) && nums[l] == nums[l + 1]) {
                        l++;
                    }
                    l++;
                    r--;
                }
            }
        }
        return temp;
    }
};